package com.longlong.controller.frontDeskApi;


import com.google.gson.Gson;
import com.longlong.config.WxGzhProperties;
import com.longlong.utils.HttpClientUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@Log4j2
@RequestMapping("/wx")
public class ApiLoginController extends ApiBaseController {

    /*
    * oppenid接口的获取
    * */
    @GetMapping("/wx_get_code")
    public Object callback(String code){
        //1.判断code是否合法
        if(StringUtils.isEmpty(code)){
            return "登录失败";
        }
        //2.通过code获取access_token
        String baseAccessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token"+
                "?appid=%s"+
                "&secret=%s"+
                "&code=%s"+
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl, WxGzhProperties.WX_OPEN_APP_ID, WxGzhProperties.WX_OPEN_APP_SECRET,code);
        System.out.println(accessTokenUrl);
        String result = null;
        try {
            //1.执行请求
            result = new HttpClientUtils().get(accessTokenUrl);
            //3.对微信返回的数据进行转换
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
            System.out.println(resultMap);
            if(resultMap.get("errcode") !=null ){
                return "登陆错误";
            }
            //4.解析微信用户的唯一凭证openid
            String openid = (String)resultMap.get("openid");
            if(StringUtils.isEmpty(openid)){
                return "登录失败";
            }
            return resultMap;
        }catch (Exception e){
            System.out.println("解析失败"+e);
            return "解析失败";
        }

    }

}
